package com.yxq.mdt.app.glide;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.blankj.utilcode.util.ImageUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.bumptech.glide.signature.ObjectKey;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.constant.Constant;


/**
 * ================================================
 *
 * @function 图片加载助手
 * Created by yd on 2019/03/07.
 * ================================================
 */
public class GlideHelper {
    /**
     * 借助内部类 实现线程安全的单例模式
     * 属于懒汉式单例，因为Java机制规定，内部类SingletonHolder只有在getInstance()
     * 方法第一次调用的时候才会被加载（实现了lazy），而且其加载过程是线程安全的。
     * 内部类加载的时候实例化一次instance。
     */
    public GlideHelper() {
    }

    private static class LoadImageHelperHolder {
        private final static GlideHelper INSTANCE = new GlideHelper();
    }

    public static GlideHelper getInstance() {
        return LoadImageHelperHolder.INSTANCE;
    }


    /**
     * 加载图片公用方法
     *
     * @param context   上下文
     * @param url       图片链接
     * @param imageView 要显示图片的控件
     */
    public static void load(Context context, String url, @NonNull ImageView imageView) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        Glide.with(context)
                .load(getImageUrl(url))
                .placeholder(R.color.gray)
                .error(R.color.gray)
                .apply(new RequestOptions().dontAnimate()).error(R.mipmap.placeholder_noraml)
                .into(imageView);

    }

    /**
     * 加载图片公用方法
     *
     * @param context    上下文
     * @param url        图片链接
     * @param resourceId 默认图片
     * @param imageView  要显示图片的控件
     */
    public static void setLoadImage(Context context, String url, @DrawableRes int resourceId, @NonNull ImageView imageView) {
        try {
            if (!isEmpty(url) && context != null) {
                Glide.with(context).load(getImageUrl(url))
                        .apply(new RequestOptions().placeholder(resourceId)
                                .dontAnimate()).error(R.mipmap.placeholder_noraml)
                        .into(imageView);
            } else {
                imageView.setImageResource(resourceId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 宽度适应屏幕 高度比例缩放
     *
     * @param context    上下文
     * @param url        图片链接
     * @param resourceId 默认图片
     * @param imageView  要显示图片的控件
     */
    public static void setLoadImageWarpHeight(Context context, String url, @DrawableRes int resourceId, @NonNull ImageView imageView) {
        if (!isEmpty(url)) {
            Glide.with(context).asBitmap().load(getImageUrl(url))
                    .apply(new RequestOptions().placeholder(R.color.gray)
                            .error(R.color.gray).dontAnimate()).error(R.mipmap.placeholder_noraml)
                    .into(new BitmapImageViewTarget(imageView) {
                        @Override
                        public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                            ViewGroup.LayoutParams para = imageView.getLayoutParams();
                            para.width = Constant.SPAN_COUNT_1_WIDTH - 10;
                            para.height = (int) (para.width * (1.0f * resource.getHeight() / resource.getWidth()));
                            imageView.setLayoutParams(para);
                            imageView.setImageBitmap(ImageUtils.toRoundCorner(resource, 20));
                        }
                    });
//                    .into(new SimpleTarget<Drawable>() {
//                        @Override
//                        public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
//                            imageView.setBackground(resource);
//                            ViewGroup.LayoutParams para = imageView.getLayoutParams();
//                            para.width = DisplayUtil.getScreenRelatedInformation(context);
//                            para.height = DisplayUtil.getScreenRelatedInformation(context) * resource.getIntrinsicHeight() / resource.getIntrinsicWidth();
//                            imageView.setLayoutParams(para);
//                        }
//                    });
        } else {
            imageView.setImageResource(resourceId);
        }
    }

    /**
     * 加载图片公用方法
     *
     * @param activity   上下文 避免长时间拥有Context
     * @param url        图片链接
     * @param resourceId 默认图片
     * @param imageView  要显示图片的控件
     */
    public static void setLoadImage(Activity activity, @NonNull String url, @DrawableRes int resourceId, @NonNull ImageView imageView) {
        if (!isEmpty(url)) {
            if (activity != null && !activity.isDestroyed()) {
                Glide.with(activity).load(getImageUrl(url))
                        .apply(new RequestOptions().placeholder(resourceId)
                                .error(resourceId).dontAnimate()).error(R.mipmap.placeholder_noraml)
                        .into(imageView);
            }
        } else {
            imageView.setImageResource(resourceId);
        }
    }

    /**
     * 加载图片公用方法
     *
     * @param activity   上下文 避免长时间拥有Context
     * @param url        图片链接
     * @param resourceId 默认图片
     * @param imageView  要显示图片的控件
     */
    public static void setLoadImageListener(Activity activity, @NonNull String url, @DrawableRes int resourceId, @NonNull ImageView imageView, CommonCallback<Object> callback) {
        if (!isEmpty(url)) {
            if (activity != null && !activity.isDestroyed()) {
                Glide.with(activity).load(getImageUrl(url))
                        .apply(new RequestOptions().placeholder(R.color.gray)
                                .error(R.color.gray).dontAnimate()).error(R.mipmap.placeholder_noraml)
                        .addListener(new RequestListener<Drawable>() {
                            @Override
                            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                                callback.onError("网络出错");
                                return false;
                            }

                            @Override
                            public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                                imageView.setImageDrawable(resource);
                                callback.onSuccess("加载成功");
                                return false;
                            }
                        }).into(imageView);
            }
        } else {
            imageView.setImageResource(resourceId);
        }
    }

    /**
     * 加载图片公用方法
     *
     * @param activity   上下文 避免长时间拥有Context
     * @param url        图片链接
     * @param resourceId 默认图片
     * @param imageView  要显示图片的控件
     */
    public static void setLoadImageNoCache(Activity activity, @NonNull String url, @DrawableRes int resourceId, @NonNull ImageView imageView) {
        if (!isEmpty(url)) {
            if (activity != null && !activity.isDestroyed()) {
                RequestOptions options = new RequestOptions().placeholder(resourceId).error(resourceId).dontAnimate().error(R.mipmap.placeholder_noraml);
                options.signature(new ObjectKey(System.currentTimeMillis()));

                Glide.with(activity).load(getImageUrl(url))
                        .apply(options)
                        .into(imageView);
            }
        } else {
            imageView.setImageResource(resourceId);
        }
    }

    /**
     * 加载圆形图片
     *
     * @param context
     * @param url
     * @param resourceId
     * @param imageView
     */
    public static void setLoadCirlcleImage(Context context, @NonNull String url, @DrawableRes int resourceId, @NonNull ImageView imageView) {
        if (context != null) {
            Glide.with(context).load(getImageUrl(url))
                    .apply(new RequestOptions().placeholder(R.color.gray)
                            .error(R.color.gray).circleCrop().dontAnimate()).error(R.mipmap.placeholder_noraml)
                    .into(imageView);
        }
    }


    /**
     * 加载圆角图片
     *
     * @param context
     * @param url
     * @param resourceId
     * @param imageView
     */
    public static void setLoadRoundImage(Context context, @NonNull String url, @DrawableRes int resourceId, @NonNull ImageView imageView) {
        if (context != null) {
            Glide.with(context).load(getImageUrl(url)).diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                    .apply(new RequestOptions().placeholder(resourceId).bitmapTransform(new RoundedCorners(20))).dontAnimate().error(R.mipmap.placeholder_noraml)
                    .into(imageView);
        }
    }

    /**
     * @param context
     * @param url
     * @param resourceId
     * @param imageView
     */
    public static void setLoadRoundAttentionImage(Context context, @NonNull String url, @DrawableRes int resourceId, @NonNull ImageView imageView) {
        if (context != null) {
            Glide.with(context).load(getImageUrl(url))
                    .apply(new RequestOptions().placeholder(resourceId)
                            .error(resourceId).fallback(resourceId).bitmapTransform(new RoundedCorners(20))).error(resourceId).dontAnimate().error(R.mipmap.placeholder_noraml)
                    .into(imageView);
        }
    }

    /**
     * 加载视频得圆角
     *
     * @param context
     * @param url
     * @param resourceId
     * @param imageView
     */
    public static void setLoadVideoImage(Context context, @NonNull String url, @DrawableRes int resourceId, @NonNull ImageView imageView) {
        if (context != null) {
            Glide.with(context).load(getImageUrl(url))
                    .apply(new RequestOptions().placeholder(R.color.gray)
                            .error(R.color.gray).bitmapTransform(new RoundedCorners(10)).dontAnimate()).error(R.mipmap.placeholder_noraml)
                    .into(imageView);
        }
    }

    /**
     * 获取图片路径的方法
     *
     * @param url 图片链接
     */
    public static String getImageUrl(String url) {
        if (!TextUtils.isEmpty(url) && url.startsWith("http://192.168.0.88")) {
            return url.replaceFirst("0", "110");
        }
        return url;
    }

    /**
     * 判断字符串是否为null或长度为0
     *
     * @param input 待校验字符串
     * @return {@code true}: 空<br> {@code false}: 不为空
     */
    public static boolean isEmpty(CharSequence input) {
        return TextUtils.isEmpty(input);
    }


    /**
     * 请求回调
     */
    public interface CommonCallback<T> {
        void onSuccess(T t);

        void onError(String errMsg);
    }
}
